<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreatemeetingAPIRequest;
use App\Http\Requests\API\UpdatemeetingAPIRequest;
use App\Http\Services\MeetingDTOBuilderService;
use App\Models\Meeting;
use App\Models\CityModel;
use App\Repositories\MeetingRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class meetingController
 * @package App\Http\Controllers\API
 */

class MeetingAPIController extends AppBaseController
{
    /** @var  meetingRepository */
    private $meetingRepository;

//    public function __construct(MeetingRepository $meetingRepo)
//    {
//        $this->meetingRepository = $meetingRepo;
//    }

    /**
     * Display a listing of the meeting.
     * GET|HEAD /meetings
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->meetingRepository->pushCriteria(new RequestCriteria($request));
        $this->meetingRepository->pushCriteria(new LimitOffsetCriteria($request));
        $meetings = $this->meetingRepository->all();

        return $this->sendResponse($meetings->toArray(), 'Meetings retrieved successfully');
    }

    /**
     * display_order asc
     * @param TicketModelRepository $repo
     */
    public function search(MeetingRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['status'] = 0;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }


        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * display_order asc
     * @param TicketModelRepository $repo
     */
    public function apiSearch(MeetingRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['status'] = 0;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        $lists = MeetingDTOBuilderService::buildMeeting($lists);

        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * @param MeetingRepository $meetingRepo
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(MeetingRepository $meetingRepo)
    {
        $input = $this->request->all();
        $this->validateInputParams('store', $input);
        $cityId = $input['city_id'];
        $city = CityModel::where('id', $cityId)->first();
        if (empty($city)) {
            return $this->error(1, '城市ID非法');
        }

        if (strtotime($input['start_time']) < time()) {
            return $this->error(1, "会议开始时间非法");
        } elseif ($input['start_time'] >= $input['end_time']) {
            return $this->error(1, "会议结束时间非法");
        }

        $input['city_name'] = $city->city;
        $userModels = $meetingRepo->create($input);

        return $this->sendResponse($userModels->toArray(), '新增会议成功');
    }

    /**
     * Display the specified meeting.
     * GET|HEAD /meetings/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, MeetingRepository $meetingRepository)
    {
        /** @var meeting $meeting */
        $meeting = $meetingRepository->findWithoutFail($id);

        if (empty($meeting)) {
            return $this->sendError('Meeting not found');
        }

        $meetingArr = $meeting->toArray();

        $meetingArr = MeetingDTOBuilderService::build($meetingArr);

        return $this->sendResponse($meetingArr, 'Meeting retrieved successfully');
    }

    /**
     * Update the specified meeting in storage.
     * PUT/PATCH /meetings/{id}
     *
     * @param  int $id
     * @param UpdatemeetingAPIRequest $request
     *
     * @return Response
     */
    public function update($id, MeetingRepository $meetingRepository)
    {
        $input = $this->request->all();
        //$this->validateInputParams('update', $input);

        $cityId = $input['city_id'] ?? 0;
        if (!empty($cityId)) {
            $city = CityModel::where('id', $cityId)->first();
            if (empty($city)) {
                return $this->error(1, '城市ID非法');
            }

            $input['city_name'] = $city->city;
        }

        /** @var meeting $meeting */
        $meeting = $meetingRepository->findWithoutFail($id);

        if (empty($meeting)) {
            return $this->sendError('Meeting not found');
        }

        $meeting = $meetingRepository->update($input, $id);

        return $this->sendResponse($meeting->toArray(), 'meeting updated successfully');
    }

    /**
     * Remove the specified meeting from storage.
     * DELETE /meetings/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var meeting $meeting */
        $meeting = $this->meetingRepository->findWithoutFail($id);

        if (empty($meeting)) {
            return $this->sendError('Meeting not found');
        }

        $meeting->delete();

        return $this->sendResponse($id, 'Meeting deleted successfully');
    }

    public function batchDestroy()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        Meeting::whereIn('id', $ids)->update(['status' => 2]);

        return $this->success([], '操作成功');
    }

    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'store' => [
            'city_id' => 'required|int',
            'start_time' => 'required|date',
            'end_time' => 'required|date',
            'tel' => 'required|string',
            'theme' => 'required|string',
            'owner' => 'required|string',
          //  'owner2' => 'sometimes|string',
            'address' => 'required|string',
            'english_name' => 'required|string',
            'name' => 'required|string',
        ],
        'update' => [
            'city_id' => 'int',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date',
            'tel' => 'string',
            'theme' => 'string',
            'owner' => 'string',
            'address' => 'string',
            'english_name' => 'string',
            'name' => 'string',
            'icon' => 'string',
            'category' => 'string',
        ],
    ];
}
